// doctor.js - 医护人员专属功能
console.log('doctor.js loaded and executing...');

// qrCodeUtils 和 utils 的占位符，如果它们没有在其他地方定义的话
// 在实际应用中，这些通常会通过导入或在单独的工具文件中定义。
const qrCodeUtils = {
    /**
     * 生成二维码并显示在指定的HTML元素中。
     * @param {string} data - 要编码到二维码中的数据。
     * @param {string} elementId - 用于显示二维码的HTML元素的ID。
     */
    generateQRCode: function(data, elementId) {
        console.log(`正在为元素 ${elementId} 生成二维码，数据为: ${data}`);
        // 二维码生成的基础占位符 - 在实际应用中，请使用 qrcode.js 等库
        const element = document.getElementById(elementId);
        if (element) {
            // 使用外部API生成二维码图片
            element.innerHTML = `<img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(data)}" alt="QR Code"/>`;
        }
    }
};

const utils = {
    /**
     * 进行语音播报。
     * @param {string} text - 要播报的文本。
     */
    speak: function(text) {
        console.log(`正在播报: ${text}`);
        // 语音合成的占位符
        if ('speechSynthesis' in window) {
            const utterance = new SpeechSynthesisUtterance(text);
            window.speechSynthesis.speak(utterance);
        }
    }
};

/**
 * 渲染急救车概览页面
 * 此函数负责构建急救车列表的UI界面，并绑定相关的搜索、筛选和操作事件
 * 实现功能：记录并查询每辆车的物资情况
 */
window.renderAmbulanceOverview = function() {
  const contentArea = document.getElementById('contentArea');
    if (!contentArea) return;

  // 构建页面HTML结构
  contentArea.innerHTML = `
        <h2 class="dashboard-title">急救车物资概览</h2>
        <div class="container-fluid mt-3">
            <div class="row mb-3">
                <!-- 操作按钮区域 -->
                <div class="col-md-6 d-flex">
                    <button class="btn btn-primary me-2" id="addAmbulanceBtn"><i class="fas fa-plus me-2"></i>添加急救车</button>
                    <button class="btn btn-success" id="scanQrCodeBtn"><i class="fas fa-qrcode me-2"></i>扫描二维码</button>
    </div>
                <!-- 搜索和筛选区域 -->
                <div class="col-md-6 text-end">
                    <input type="text" class="form-control d-inline-block w-auto me-2" id="ambulanceSearchInput" placeholder="搜索急救车编号、科室、状态、位置..." />
                    <select class="form-select d-inline-block w-auto" id="ambulanceStatusFilter">
                        <option value="all">所有状态</option>
                        <option value="可用">可用</option>
                        <option value="使用中">使用中</option>
                        <option value="维护中">维护中</option>
                        <option value="维修中">维修中</option>
                    </select>
    </div>
    </div>
            <!-- 急救车列表表格 -->
            <h4 class="section-title mt-4"><i class="fas fa-ambulance me-2"></i>急救车列表</h4>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>编号</th>
                            <th>科室</th>
                            <th>状态</th>
                            <th>位置</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="ambulanceListTableBody">
                    </tbody>
                </table>
    </div>
    </div>
        <!-- Modals for details and layers will be created dynamically -->
    `;

    // 绑定事件监听器
    document.getElementById('ambulanceSearchInput').addEventListener('input', searchAmbulances);
    document.getElementById('ambulanceStatusFilter').addEventListener('change', searchAmbulances);
    document.getElementById('addAmbulanceBtn').addEventListener('click', addAmbulance);
    document.getElementById('scanQrCodeBtn').addEventListener('click', scanQrCode);

    // 初始加载急救车列表
    loadAmbulancesList();
};

/**
 * 根据急救车物资状态获取对应的Bootstrap徽章CSS类
 * @param {string} status - 物资状态（如：'可用', '使用中', '维护中', '维修中', '临期', '库存不足', '正常', '已过期'）
 * @returns {string} - 对应的Bootstrap背景颜色类
 */
function getStatusBadgeClass(status) {
    switch (status) {
        case '可用': return 'success';      // 绿色 - 可用状态
        case '使用中': return 'warning';    // 黄色 - 使用中状态
        case '维护中': return 'info';       // 蓝色 - 维护中状态
        case '维修中': return 'danger';     // 红色 - 维修中状态
        case '临期': return 'warning';      // 黄色 - 即将过期
        case '库存不足': return 'danger';   // 红色 - 库存不足
        case '正常': return 'success';      // 绿色 - 正常状态
        case '已过期': return 'dark';       // 深色 - 已过期状态
        default: return 'secondary';        // 灰色 - 默认状态
    }
}

/**
 * 加载并渲染急救车列表
 * 从全局mockData中获取急救车数据，并将其显示在表格中
 * 同时为每个急救车的操作按钮绑定事件
 */
function loadAmbulancesList() {
    const ambulanceListTableBody = document.getElementById('ambulanceListTableBody');
    // 如果表格体不存在，则退出
    if (!ambulanceListTableBody) return;

    const ambulances = window.mockData.ambulances; // 获取急救车数据

    // 使用map函数将急救车数据转换为HTML表格行，并用join连接
    ambulanceListTableBody.innerHTML = ambulances.map(ambulance => {
        // 获取急救车的总体物资供应状态
        const overallSupplyStatus = getAmbulanceOverallSupplyStatus(ambulance);
        const displayStatusText = `物资${overallSupplyStatus}`; // 显示的文本

        return `
            <tr data-ambulance-id="${ambulance.id}" style="cursor: pointer;">
                <td>${ambulance.plateNumber}</td>
                <td>${ambulance.department}</td>
                <td><span class="badge bg-${getStatusBadgeClass(overallSupplyStatus)}">${displayStatusText}</span></td>
                <td>${ambulance.location}</td>
                <td>
                    <!-- 操作按钮组 -->
                    <button class="btn btn-info btn-sm view-details-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-eye"></i></button>
                    <button class="btn btn-warning btn-sm edit-ambulance-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-edit"></i></button>
                    <button class="btn btn-danger btn-sm delete-ambulance-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-trash-alt"></i></button>
                    <button class="btn btn-primary btn-sm manage-layers-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-layer-group me-1"></i>层级管理</button>
                    <button class="btn btn-primary btn-sm view-usage-records-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-history me-1"></i>查看使用记录</button>
                    <button class="btn btn-success btn-sm add-usage-record-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-plus me-1"></i>添加使用记录</button>
                    <button class="btn btn-secondary btn-sm close-ambulance-btn" data-ambulance-id="${ambulance.id}">关闭</button>
                </td>
        </tr>
        `;
    }).join('');

    // 为所有操作按钮绑定点击事件
    document.querySelectorAll('.view-details-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation(); // 阻止行点击事件触发
            showAmbulanceDetails(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.edit-ambulance-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            editAmbulance(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.delete-ambulance-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            deleteAmbulance(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.manage-layers-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            showLayerManagementModal(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.view-usage-records-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            showAmbulanceUsageRecords(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.add-usage-record-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            showAddAmbulanceUsageRecordModal(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.close-ambulance-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            closeAmbulance(this.dataset.ambulanceId);
        });
    });

    // 绑定行点击事件（除了按钮之外的区域）
    document.querySelectorAll('#ambulanceListTableBody tr').forEach(row => {
        row.addEventListener('click', function(event) {
            // 检查点击目标是否是按钮或在按钮内部
            if (!event.target.closest('button')) {
                showAmbulanceDetails(this.dataset.ambulanceId);
            }
        });
    });
}

/**
 * 根据搜索词和状态筛选急救车列表
 * 此函数会实时响应输入和选择的变化，更新显示的急救车列表
 */
function searchAmbulances() {
    const searchTerm = document.getElementById('ambulanceSearchInput').value.toLowerCase();
    const statusFilter = document.getElementById('ambulanceStatusFilter').value;
    const ambulanceListTableBody = document.getElementById('ambulanceListTableBody');
    if (!ambulanceListTableBody) return;

    // 筛选急救车数据
    let filteredAmbulances = window.mockData.ambulances.filter(ambulance => {
        // 搜索条件：编号、科室、位置、状态
        const matchesSearch = (
            ambulance.plateNumber.toLowerCase().includes(searchTerm) ||
            ambulance.department.toLowerCase().includes(searchTerm) ||
            ambulance.location.toLowerCase().includes(searchTerm) ||
            ambulance.status.toLowerCase().includes(searchTerm)
        );
        // 状态筛选条件
        const overallSupplyStatus = getAmbulanceOverallSupplyStatus(ambulance);
        const matchesStatus = (statusFilter === 'all' || ambulance.status === statusFilter || overallSupplyStatus === statusFilter);
        
        return matchesSearch && matchesStatus;
    });

    ambulanceListTableBody.innerHTML = filteredAmbulances.map(ambulance => {
        const overallSupplyStatus = getAmbulanceOverallSupplyStatus(ambulance);
        const displayStatusText = `物资${overallSupplyStatus}`;
        return `
            <tr data-ambulance-id="${ambulance.id}" style="cursor: pointer;">
                <td>${ambulance.plateNumber}</td>
                <td>${ambulance.department}</td>
                <td><span class="badge bg-${getStatusBadgeClass(overallSupplyStatus)}">${displayStatusText}</span></td>
                <td>${ambulance.location}</td>
                <td>
                    <button class="btn btn-info btn-sm view-details-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-eye"></i></button>
                    <button class="btn btn-warning btn-sm edit-ambulance-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-edit"></i></button>
                    <button class="btn btn-danger btn-sm delete-ambulance-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-trash-alt"></i></button>
                    <button class="btn btn-primary btn-sm manage-layers-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-layer-group me-1"></i>层级管理</button>
                    <button class="btn btn-primary btn-sm view-usage-records-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-history me-1"></i>查看使用记录</button>
                    <button class="btn btn-success btn-sm add-usage-record-btn me-1" data-ambulance-id="${ambulance.id}"><i class="fas fa-plus me-1"></i>添加使用记录</button>
                    <button class="btn btn-secondary btn-sm close-ambulance-btn" data-ambulance-id="${ambulance.id}">关闭</button>
                </td>
        </tr>
        `;
    }).join('');

    // 重新绑定事件，因为 innerHTML 被替换了
    document.querySelectorAll('.view-details-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            showAmbulanceDetails(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.edit-ambulance-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            editAmbulance(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.delete-ambulance-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            deleteAmbulance(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.manage-layers-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            showLayerManagementModal(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.view-usage-records-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            showAmbulanceUsageRecords(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.add-usage-record-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            showAddAmbulanceUsageRecordModal(this.dataset.ambulanceId);
        });
    });
    document.querySelectorAll('.close-ambulance-btn').forEach(button => {
        button.addEventListener('click', function(event) {
            event.stopPropagation();
            closeAmbulance(this.dataset.ambulanceId);
        });
    });

    document.querySelectorAll('#ambulanceListTableBody tr').forEach(row => {
        row.addEventListener('click', function(event) {
            if (!event.target.closest('button')) {
                showAmbulanceDetails(this.dataset.ambulanceId);
            }
        });
    });
}

/**
 * 显示急救车详情的模态框。
 * 该函数根据急救车ID查找对应的急救车数据，并动态构建一个模态框来展示其详细信息，包括物资分层信息。
 * @param {string} id - 急救车的唯一标识ID。
 */
function showAmbulanceDetails(id) {
    const ambulance = window.mockData.ambulances.find(a => a.id === id);
    // 如果找不到急救车，则退出
    if (!ambulance) return;

    // 创建模态框元素
    const modal = document.createElement('div');
    modal.className = 'modal fade show';
    modal.style.display = 'block';
    // 设置模态框的HTML内容
    modal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">急救车详情</h5>
                    <button type="button" class="btn-close" onclick="this.closest('.modal').remove()"></button>
                </div>
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-6">
                            <div id="ambulanceQRCode"></div>
                        </div>
                        <div class="col-6">
                            <p><strong>编号：</strong>${ambulance.plateNumber}</p>
                            <p><strong>科室：：</strong>${ambulance.department}</p>
                            <p><strong>运营状态：：</strong><span class="badge bg-${getStatusBadgeClass(ambulance.status)}">${ambulance.status}</span></p>
                            <p><strong>物资状态：：</strong><span class="badge bg-${getStatusBadgeClass(getAmbulanceOverallSupplyStatus(ambulance))}">物资${getAmbulanceOverallSupplyStatus(ambulance)}</span></p>
                            <p><strong>位置：：</strong>${ambulance.location}</p>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12">
                            <h6>层级信息</h6>
                            <div class="table-responsive">
                                <table class="table table-sm">
      <thead>
        <tr>
                                            <th>层级名称</th>
                                            <th>描述</th>
                                            <th>物品数量</th>
                                            <th>物资状态</th>
                                            <th>操作</th>
        </tr>
      </thead>
      <tbody>
                                        ${ambulance.layers.map(layer => {
                                            // 计算该层级的物资状态
                                            const layerItems = layer.items || [];
                                            const layerStatus = getLayerOverallStatus(layerItems);
                                            return `
                                                <tr>
                                                    <td>${layer.name}</td>
                                                    <td>${layer.description}</td>
                                                    <td>${layerItems.length}</td>
                                                    <td><span class="badge bg-${getStatusBadgeClass(layerStatus)}">物资${layerStatus}</span></td>
                                                    <td>
                                                        <button class="btn btn-sm btn-info" onclick="showLayerDetails('${ambulance.id}', '${layer.id}')">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                    </td>
          </tr>
                                            `;
                                        }).join('')}
      </tbody>
    </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-info" onclick="showLayerManagementModal('${ambulance.id}')">
                        <i class="fas fa-layer-group me-2"></i>层级管理
                    </button>
                    <button type="button" class="btn btn-primary" onclick="showAmbulanceUsageRecords('${ambulance.id}')">
                        <i class="fas fa-history me-2"></i>查看使用记录
                    </button>
                    <button type="button" class="btn btn-success" onclick="showAddAmbulanceUsageRecordModal('${ambulance.id}')">
                        <i class="fas fa-plus me-2"></i>添加使用记录
                    </button>
                    <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">关闭</button>
                </div>
            </div>
        </div>
    `;

    // 将模态框添加到文档体
    document.body.appendChild(modal);

    // 生成二维码
    qrCodeUtils.generateQRCode(JSON.stringify({
        type: 'ambulance',
        id: id
    }), 'ambulanceQRCode');

    // 语音播报急救车详情
    utils.speak(`查看急救车详情：${ambulance.plateNumber}`);
}

/**
 * 获取层级的总体物资状态。
 * 优先级：已过期 > 临期 > 库存不足 > 正常。
 * @param {Array} items - 层级内的物资项数组。
 * @returns {string} - 层级的总体物资状态。
 */
function getLayerOverallStatus(items) {
    let hasExpired = false; // 是否存在已过期物资
    let hasExpiringSoon = false; // 是否存在临期物资
    let hasLowStock = false; // 是否存在库存不足物资
    let hasNormal = false; // 是否存在正常物资
    let hasAnyItem = items.length > 0; // 该层级是否有任何物资

    // 遍历层级内的所有物资项，检查其状态
    for (const item of items) {
        if (item.status === '已过期') {
            hasExpired = true;
            break; // 发现已过期物资，直接跳出，因为这是最高优先级
        }
        if (item.status === '临期') {
            hasExpiringSoon = true;
        }
        if (item.status === '库存不足') {
            hasLowStock = true;
        }
        if (item.status === '正常') {
            hasNormal = true;
        }
    }

    // 根据优先级返回总体状态
    if (hasExpired) return '已过期';
    if (hasExpiringSoon) return '临期';
    if (hasLowStock) return '库存不足';
    if (hasAnyItem || hasNormal) return '正常'; // 如果有任何物资且无问题，或有正常物资，则为正常
    return '正常'; // 如果没有物资，也视为正常（或者可以定义为"无物资"）
}

/**
 * 显示指定层级的详细信息模态框。
 * 该函数根据急救车ID和层级ID查找对应的层级数据，并动态构建一个模态框来展示其包含的物资列表。
 * @param {string} ambulanceId - 急救车的唯一标识ID。
 * @param {string} layerId - 层级的唯一标识ID。
 */
function showLayerDetails(ambulanceId, layerId) {
    const ambulance = window.mockData.ambulances.find(a => a.id === ambulanceId);
    if (!ambulance) return;

    const layer = ambulance.layers.find(l => l.id === layerId);
    if (!layer) return;

    const modal = document.createElement('div');
    modal.className = 'modal fade show';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">层级详情 - ${layer.name}</h5>
                    <button type="button" class="btn-close" onclick="this.closest('.modal').remove()"></button>
                </div>
                <div class="modal-body">
                    <p><strong>描述：</strong>${layer.description}</p>
                    <div class="table-responsive">
                        <table class="table table-sm">
      <thead>
        <tr>
                                    <th>物品名称</th>
          <th>数量</th>
                                    <th>状态</th>
        </tr>
      </thead>
      <tbody>
                                ${layer.items.map(item => `
                                    <tr>
                                        <td>${item.name}</td>
                                        <td>${item.quantity}</td>
                                        <td>
                                            <span class="badge bg-${getStatusBadgeClass(item.status)}">
                                                ${item.status}
                                            </span>
                                        </td>
          </tr>
        `).join('')}
      </tbody>
    </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">关闭</button>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(modal);
}

/**
 * 显示添加物资的模态框。
 * 此模态框用于向库存中添加新的物资项。
 */
function showAddInventoryModal() {
    const modal = document.createElement('div');
    modal.className = 'modal fade show';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加物资</h5>
                    <button type="button" class="btn-close" onclick="this.closest('.modal').remove()"></button>
                </div>
                <div class="modal-body">
                    <form id="addInventoryForm">
                        <div class="mb-3">
                            <label class="form-label">物资名称</label>
                            <input type="text" class="form-control" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">类型</label>
                            <select class="form-select" name="category" required>
                                <option value="急救药品">急救药品</option>
                                <option value="基础药品">基础药品</option>
                                <option value="医疗设备">医疗设备</option>
                                <option value="手术器械">手术器械</option>
                                <option value="消毒用品">消毒用品</option>
                                <option value="手术耗材">手术耗材</option>
                                <option value="医疗耗材">医疗耗材</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">数量</label>
                            <input type="number" class="form-control" name="quantity" required min="0">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">最低数量</label>
                            <input type="number" class="form-control" name="minQuantity" required min="0">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">有效期</label>
                            <input type="date" class="form-control" name="expiryDate" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">位置</label>
                            <input type="text" class="form-control" name="location" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveInventory()">保存</button>
                </div>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
}

// 占位符函数：新增急救车功能（待实现）
function addAmbulance() {
    showToast('info', '新增急救车功能待实现');
    console.log('新增急救车');
}

// 占位符函数：扫描二维码功能（待实现）
function scanQrCode() {
    showToast('info', '扫描二维码功能待实现');
    console.log('扫描二维码');
}

// 占位符函数：编辑急救车功能（待实现）
function editAmbulance(ambulanceId) {
    showToast('info', `编辑急救车 ${ambulanceId} 功能待实现`);
    console.log('编辑急救车:', ambulanceId);
}

// 占位符函数：删除急救车功能（待实现）
function deleteAmbulance(ambulanceId) {
    showToast('info', `删除急救车 ${ambulanceId} 功能待实现`);
    console.log('删除急救车:', ambulanceId);
}

// 占位符函数：层级管理功能（由 showAmbulanceDetails 模态框调用，待实现）
function showLayerManagementModal(ambulanceId) {
    showToast('info', `层级管理功能待实现，急救车ID: ${ambulanceId}`);
    console.log('层级管理:', ambulanceId);
}

/**
 * 显示急救车使用记录模态框。
 * @param {string} ambulanceId - 急救车ID。
 */
function showAmbulanceUsageRecords(ambulanceId) {
    const ambulance = window.mockData.ambulances.find(a => a.id === ambulanceId);
    if (!ambulance) return;

    // 获取该急救车的使用记录
    const records = window.mockData.usageRecords.filter(record => record.ambulanceId === ambulanceId);

    // 获取当前日期，格式化为 YYYY-MM-DD
    const today = new Date().toISOString().split('T')[0];

    const modal = document.createElement('div');
    modal.className = 'modal fade show';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">急救车使用记录 - ${ambulance.plateNumber}</h5>
                    <button type="button" class="btn-close" onclick="this.closest('.modal').remove()"></button>
                </div>
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <input type="text" class="form-control" id="recordSearchInput" placeholder="搜索操作人、患者信息、位置..." style="height: 38px;">
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" id="recordTypeFilter" style="height: 38px;">
                                <option value="all">所有类型</option>
                                <option value="出库">出库记录</option>
                                <option value="入库">入库记录</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <input type="date" class="form-control" id="recordDateFilter" value="${today}" style="height: 38px;">
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover">
      <thead>
        <tr>
                                    <th>操作时间</th>
                                    <th>类型</th>
                                    <th>操作人</th>
                                    <th>患者信息</th>
                                    <th>位置</th>
                                    <th>物资明细</th>
                                    <th>备注</th>
        </tr>
      </thead>
                            <tbody id="usageRecordsTableBody">
                                ${records.map(record => `
                                    <tr>
                                        <td>${record.operationTime}</td>
                                        <td><span class="badge bg-${record.type === '出库' ? 'danger' : 'success'}">${record.type}</span></td>
                                        <td>${record.operator}</td>
                                        <td>${record.patientInfo || '-'}</td>
                                        <td>${record.location}</td>
                                        <td>
                                            <button class="btn btn-sm btn-info" onclick="showRecordItems('${record.id}')">
                                                <i class="fas fa-list"></i> 查看明细
                                            </button>
                                        </td>
                                        <td>${record.notes || '-'}</td>
          </tr>
        `).join('')}
      </tbody>
    </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-success" onclick="showAddAmbulanceUsageRecordModal('${ambulanceId}')">
                        <i class="fas fa-plus me-2"></i>添加使用记录
                    </button>
                    <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">关闭</button>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(modal);

    // 绑定搜索和筛选事件
    document.getElementById('recordSearchInput').addEventListener('input', () => filterUsageRecords(ambulanceId));
    document.getElementById('recordTypeFilter').addEventListener('change', () => filterUsageRecords(ambulanceId));
    document.getElementById('recordDateFilter').addEventListener('change', () => filterUsageRecords(ambulanceId));
}

/**
 * 显示使用记录中的物资明细。
 * @param {string} recordId - 使用记录ID。
 */
function showRecordItems(recordId) {
    const record = window.mockData.usageRecords.find(r => r.id === recordId);
    if (!record) return;

    const modal = document.createElement('div');
    modal.className = 'modal fade show';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">物资明细 - 记录编号: ${record.id}</h5>
                    <button type="button" class="btn-close" onclick="this.closest('.modal').remove()"></button>
                </div>
                <div class="modal-body">
                    <p><strong>操作类型：</strong> <span class="badge bg-${record.type === '出库' ? 'danger' : 'success'}">${record.type}</span></p>
                    <p><strong>操作人：</strong> ${record.operator}</p>
                    <p><strong>操作时间：</strong> ${new Date(record.operationTime).toLocaleString()}</p>
                    ${record.patientInfo ? `<p><strong>患者信息：</strong> ${record.patientInfo}</p>` : ''}
                    ${record.location ? `<p><strong>地点：</strong> ${record.location}</p>` : ''}
                    ${record.notes ? `<p><strong>备注：</strong> ${record.notes}</p>` : ''}
                    
                    <h6>物资列表</h6>
                    <div class="table-responsive">
                        <table class="table table-sm">
      <thead>
        <tr>
                                    <th>物资名称</th>
          <th>数量</th>
                                    <th>单位</th>
        </tr>
      </thead>
      <tbody>
                                ${record.items.map(item => `
                                    <tr>
                                        <td>${item.name}</td>
                                        <td>${item.quantity}</td>
                                        <td>${item.unit}</td>
          </tr>
        `).join('')}
      </tbody>
    </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">关闭</button>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(modal);
}

/**
 * 筛选使用记录。
 * @param {string} ambulanceId - 急救车ID。
 */
function filterUsageRecords(ambulanceId) {
    const searchTerm = document.getElementById('recordSearchInput').value.toLowerCase();
    const typeFilter = document.getElementById('recordTypeFilter').value;
    const dateFilter = document.getElementById('recordDateFilter').value;
    const records = window.mockData.usageRecords.filter(record => record.ambulanceId === ambulanceId);

    const filteredRecords = records.filter(record => {
        const matchesSearch = (
            record.operator.toLowerCase().includes(searchTerm) ||
            (record.patientInfo && record.patientInfo.toLowerCase().includes(searchTerm)) ||
            record.location.toLowerCase().includes(searchTerm) ||
            record.notes.toLowerCase().includes(searchTerm)
        );
        const matchesType = typeFilter === 'all' || record.type === typeFilter;
        const matchesDate = !dateFilter || record.operationTime.startsWith(dateFilter);

        return matchesSearch && matchesType && matchesDate;
    });

    const tbody = document.getElementById('usageRecordsTableBody');
    if (tbody) {
        tbody.innerHTML = filteredRecords.map(record => `
            <tr>
                <td>${record.operationTime}</td>
                <td><span class="badge bg-${record.type === '出库' ? 'danger' : 'success'}">${record.type}</span></td>
                <td>${record.operator}</td>
                <td>${record.patientInfo || '-'}</td>
                <td>${record.location}</td>
                <td>
                    <button class="btn btn-sm btn-info" onclick="showRecordItems('${record.id}')">
                        <i class="fas fa-list"></i> 查看明细
                    </button>
                </td>
                <td>${record.notes || '-'}</td>
        </tr>
        `).join('');
    }
}

// 占位符函数：添加使用记录 (由 showAmbulanceDetails 模态框调用)
function showAddAmbulanceUsageRecordModal(ambulanceId) {
    showToast('info', `添加使用记录功能待实现，急救车ID: ${ambulanceId}`);
    console.log('添加使用记录:', ambulanceId);
}

// 占位符函数：关闭急救车 (如果表示停用或归库)
function closeAmbulance(ambulanceId) {
    showToast('info', `关闭急救车 ${ambulanceId} 功能待实现`);
    console.log('关闭急救车:', ambulanceId);
}

// 占位符函数：编辑物资项 (未在当前提供的代码中使用，但保留以防将来需要)
function editSupplyItem(itemId, ambulanceId, layerId) {
    showToast('info', `编辑物资 ${itemId} (急救车: ${ambulanceId}, 层级: ${layerId}) 功能待实现`);
    console.log('编辑物资项:', itemId, ambulanceId, layerId);
}

// 占位符函数：删除物资项 (未在当前提供的代码中使用，但保留以防将来需要)
function deleteSupplyItem(itemId, ambulanceId, layerId) {
    showToast('info', `删除物资 ${itemId} (急救车: ${ambulanceId}, 层级: ${layerId}) 功能待实现`);
    console.log('删除物资项:', itemId, ambulanceId, layerId);
}

// 占位符函数：保存物资 (由 showAddInventoryModal 调用)
function saveInventory() {
    showToast('info', '保存物资功能待实现');
    console.log('保存物资');
}

// 通用 Toast 提示函数 (确保与admin.js一致)
function showToast(type, message) {
    const toastContainer = document.getElementById('toastContainer') || (() => {
        const div = document.createElement('div');
        div.id = 'toastContainer';
        div.style.position = 'fixed';
        div.style.top = '20px';
        div.style.right = '20px';
        div.style.zIndex = '1050';
        document.body.appendChild(div);
        return div;
    })();

    const toastId = `toast-${Date.now()}`;
    const toastHtml = `
        <div id="${toastId}" class="toast align-items-center text-white bg-${type} border-0" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="3000">
            <div class="d-flex">
                <div class="toast-body">${message}</div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
    `;

    toastContainer.insertAdjacentHTML('beforeend', toastHtml);
    const toastEl = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastEl);
    toast.show();

    // 自动移除toast以避免DOM臃肿
    toastEl.addEventListener('hidden.bs.toast', function () {
        toastEl.remove();
    });
}

/**
 * 获取急救车的总体物资状态。
 * 优先级：已过期 > 临期 > 库存不足 > 正常。
 * @param {object} ambulance - 急救车对象。
 * @returns {string} - 急救车的总体物资状态（例如：'已过期', '临期', '库存不足', '正常'）。
 */
function getAmbulanceOverallSupplyStatus(ambulance) {
    let hasExpired = false;
    let hasExpiringSoon = false;
    let hasLowStock = false;
    let hasNormal = false; // To track if there's at least one '正常' item if no critical issues
    let hasAnyItem = false; // To track if the ambulance has any items at all

    if (ambulance.layers && ambulance.layers.length > 0) {
        for (const layer of ambulance.layers) {
            if (layer.items && layer.items.length > 0) {
                hasAnyItem = true;
                for (const item of layer.items) {
                    if (item.status === '已过期') {
                        hasExpired = true;
                        break; // 发现已过期物资，最高优先级
                    }
                    if (item.status === '临期') {
                        hasExpiringSoon = true;
                    }
                    if (item.status === '库存不足') {
                        hasLowStock = true;
                    }
                    if (item.status === '正常') {
                        hasNormal = true;
                    }
                }
            }
            if (hasExpired) break; // 如果已发现过期物资，则跳出所有循环
        }
    }

    if (hasExpired) return '已过期'; // 优先显示已过期
    if (hasExpiringSoon) return '临期'; // 其次显示临期
    if (hasLowStock) return '库存不足'; // 再次显示库存不足
    
    // 如果没有任何问题物资，则根据是否有任何物资来判断
    if (hasAnyItem || hasNormal) return '正常'; // 如果有任何物资且无问题，或有正常物资，则为正常
    return '正常'; // 如果没有物资，也视为正常（或者可以定义为"无物资"）
}

// 渲染物资出库/使用登记页面
window.renderMaterialOutboundRegistration = function() {
    const contentDiv = document.getElementById('contentArea');
    contentDiv.innerHTML = `
        <h2 class="mb-4">物资出库/使用登记</h2>
        <div class="card">
            <div class="card-body">
                <form id="materialRegistrationForm">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="ambulanceSelect" class="form-label">选择急救车</label>
                            <select id="ambulanceSelect" class="form-select" required>
                                <option value="">请选择急救车</option>
                                <!-- 急救车选项将在此处加载 -->
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="operationType" class="form-label">操作类型</label>
                            <select id="operationType" class="form-select" required>
                                <option value="">请选择操作类型</option>
                                <option value="出库">出库</option>
                                <option value="入库">入库</option>
                            </select>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">物资详情</label>
                        <div id="materialItemsContainer">
                            <!-- 动态添加物资输入行 -->
                            <div class="input-group mb-2 material-item-row">
                                <input type="text" class="form-control item-id" placeholder="物资ID" required>
                                <input type="text" class="form-control item-name" placeholder="物资名称" required>
                                <input type="number" class="form-control item-quantity" placeholder="数量" required min="1">
                                <input type="text" class="form-control item-unit" placeholder="单位" required>
                                <button type="button" class="btn btn-danger remove-item-btn">删除</button>
                            </div>
                        </div>
                        <button type="button" class="btn btn-success mt-2" id="addMaterialItemBtn">添加物资</button>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="operatorName" class="form-label">操作员</label>
                            <input type="text" id="operatorName" class="form-control" value="${window.currentUser ? window.currentUser.username : ''}" required>
                        </div>
                        <div class="col-md-6">
                            <label for="operationTime" class="form-label">操作时间</label>
                            <input type="datetime-local" id="operationTime" class="form-control" required>
                        </div>
                    </div>

                    <div class="mb-3" id="patientInfoGroup">
                        <label for="patientInfo" class="form-label">患者信息</label>
                        <input type="text" id="patientInfo" class="form-control" placeholder="患者姓名，性别，年龄，病情等">
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="location" class="form-label">地点</label>
                            <input type="text" id="location" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label for="notes" class="form-label">备注</label>
                            <textarea id="notes" class="form-control" rows="2"></textarea>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary">提交登记</button>
                </form>
            </div>
        </div>
    `;

    // 填充急救车下拉列表
    const ambulanceSelect = document.getElementById('ambulanceSelect');
    window.mockData.ambulances.forEach(ambulance => {
        const option = document.createElement('option');
        option.value = ambulance.id;
        option.textContent = `${ambulance.plateNumber} (${ambulance.department} - ${ambulance.location})`;
        ambulanceSelect.appendChild(option);
    });

    // 设置默认操作时间为当前时间
    const now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset()); // Adjust for timezone offset
    document.getElementById('operationTime').value = now.toISOString().slice(0, 16);

    // 根据操作类型显示/隐藏患者信息
    const operationTypeSelect = document.getElementById('operationType');
    const patientInfoGroup = document.getElementById('patientInfoGroup');
    operationTypeSelect.addEventListener('change', function() {
        if (this.value === '出库') {
            patientInfoGroup.style.display = 'block';
        } else {
            patientInfoGroup.style.display = 'none';
            document.getElementById('patientInfo').value = ''; // 清空患者信息
        }
    });
    // 初始设置
    if (operationTypeSelect.value !== '出库') {
        patientInfoGroup.style.display = 'none';
    }

    // 添加物资按钮事件
    document.getElementById('addMaterialItemBtn').addEventListener('click', addMaterialItemField);

    // 删除物资按钮事件（事件委托）
    document.getElementById('materialItemsContainer').addEventListener('click', function(event) {
        if (event.target.classList.contains('remove-item-btn')) {
            event.target.closest('.material-item-row').remove();
        }
    });

    // 表单提交事件
    document.getElementById('materialRegistrationForm').addEventListener('submit', submitMaterialRegistration);
};

// 动态添加物资输入行
function addMaterialItemField() {
    const container = document.getElementById('materialItemsContainer');
    const newRow = document.createElement('div');
    newRow.classList.add('input-group', 'mb-2', 'material-item-row');
    newRow.innerHTML = `
        <input type="text" class="form-control item-id" placeholder="物资ID" required>
        <input type="text" class="form-control item-name" placeholder="物资名称" required>
        <input type="number" class="form-control item-quantity" placeholder="数量" required min="1">
        <input type="text" class="form-control item-unit" placeholder="单位" required>
        <button type="button" class="btn btn-danger remove-item-btn">删除</button>
    `;
    container.appendChild(newRow);
}

/**
 * 物资出库/使用登记表单提交处理函数
 * 实现功能：记录物资的正常使用和损耗情况
 * @param {Event} event - 表单提交事件对象
 */
function submitMaterialRegistration(event) {
    event.preventDefault(); // 阻止表单默认提交行为

    // 获取表单数据
    const form = event.target;
    const ambulanceId = form.ambulanceSelect.value;        // 急救车ID
    const operationType = form.operationType.value;        // 操作类型（出库/入库）
    const operator = form.operatorName.value;              // 操作员姓名
    const operationTime = form.operationTime.value;        // 操作时间
    const patientInfo = form.patientInfo.value;            // 患者信息（仅出库时填写）
    const location = form.location.value;                  // 操作地点
    const notes = form.notes.value;                        // 备注信息

    // 收集物资明细信息
    const items = [];
    document.querySelectorAll('#materialItemsContainer .material-item-row').forEach(row => {
        const itemId = row.querySelector('.item-id').value;           // 物资ID
        const itemName = row.querySelector('.item-name').value;       // 物资名称
        const itemQuantity = parseInt(row.querySelector('.item-quantity').value); // 数量
        const itemUnit = row.querySelector('.item-unit').value;       // 单位
        
        // 验证物资信息完整性
        if (itemId && itemName && itemQuantity && itemUnit) {
            items.push({
                id: itemId,
                name: itemName,
                quantity: itemQuantity,
                unit: itemUnit
            });
        }
    });

    // 验证是否至少添加了一项物资
    if (items.length === 0) {
        showToast('error', '请至少添加一项物资');
        return;
    }

    // 创建新的使用记录对象
    const newRecord = {
        id: 'UR' + Date.now(), // 生成唯一记录ID：UR + 时间戳
        ambulanceId: ambulanceId,
        type: operationType,
        operator: operator,
        operationTime: operationTime,
        patientInfo: operationType === '出库' ? patientInfo : '', // 仅出库时记录患者信息
        location: location,
        notes: notes,
        items: items
    };

    // 初始化使用记录数组（如果不存在）
    if (!window.mockData.usageRecords) {
        window.mockData.usageRecords = [];
    }
    // 将新记录添加到数组开头（最新的记录显示在前面）
    window.mockData.usageRecords.unshift(newRecord);

    // 显示成功提示
    showToast('success', '物资登记成功！');
    
    // 重置表单
    form.reset();
    
    // 重新设置操作时间为当前时间
    const now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    document.getElementById('operationTime').value = now.toISOString().slice(0, 16);

    // 清空动态添加的物资行，只保留一个空行
    const materialItemsContainer = document.getElementById('materialItemsContainer');
    materialItemsContainer.innerHTML = `
        <div class="input-group mb-2 material-item-row">
            <input type="text" class="form-control item-id" placeholder="物资ID" required>
            <input type="text" class="form-control item-name" placeholder="物资名称" required>
            <input type="number" class="form-control item-quantity" placeholder="数量" required min="1">
            <input type="text" class="form-control item-unit" placeholder="单位" required>
            <button type="button" class="btn btn-danger remove-item-btn">删除</button>
        </div>
    `;
    
    // 重新隐藏患者信息（如果操作类型不是出库）
    const operationTypeSelect = document.getElementById('operationType');
    const patientInfoGroup = document.getElementById('patientInfoGroup');
    if (operationTypeSelect.value !== '出库') {
        patientInfoGroup.style.display = 'none';
    }

    // 如果当前页面是物资使用历史，则刷新列表
    if (document.getElementById('usageHistoryTableBody')) {
        loadUsageHistoryList();
    }
}

/**
 * 渲染物资申领/补充申请页面
 * 实现功能：记录物资的补充情况
 */
window.renderMaterialRequisition = function() {
    const contentDiv = document.getElementById('contentArea');
    contentDiv.innerHTML = `
        <h2 class="mb-4">物资申领/补充申请</h2>
        <div class="row mb-4">
            <!-- 新建申请按钮 -->
            <div class="col-md-6">
                <button class="btn btn-primary" onclick="showNewRequisitionModal()">
                    <i class="fas fa-plus me-2"></i>新建申请
                </button>
            </div>
            <!-- 搜索和筛选区域 -->
            <div class="col-md-6">
                <div class="input-group">
                    <input type="text" class="form-control" id="requisitionSearchInput" placeholder="搜索申请编号、物资名称...">
                    <select class="form-select" id="requisitionStatusFilter" style="max-width: 150px;">
                        <option value="all">所有状态</option>
                        <option value="待审批">待审批</option>
                        <option value="已批准">已批准</option>
                        <option value="已拒绝">已拒绝</option>
                        <option value="已完成">已完成</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 申请列表表格 -->
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>申请编号</th>
                                <th>申请类型</th>
                                <th>申请时间</th>
                                <th>申请人</th>
                                <th>申请科室</th>
                                <th>物资数量</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="requisitionListTableBody">
                            <!-- 申请列表将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;

    // 初始化申请列表
    loadRequisitionList();
    
    // 添加搜索和筛选事件监听
    document.getElementById('requisitionSearchInput').addEventListener('input', filterRequisitions);
    document.getElementById('requisitionStatusFilter').addEventListener('change', filterRequisitions);
};

/**
 * 显示新建申请模态框
 * 创建物资申领或补充申请的弹窗界面
 */
function showNewRequisitionModal() {
    const modal = document.createElement('div');
    modal.className = 'modal fade show';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">新建物资申请</h5>
                    <button type="button" class="btn-close" onclick="this.closest('.modal').remove()"></button>
                </div>
                <div class="modal-body">
                    <form id="requisitionForm">
                        <!-- 申请基本信息 -->
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="requisitionType" class="form-label">申请类型</label>
                                <select id="requisitionType" class="form-select" required>
                                    <option value="">请选择申请类型</option>
                                    <option value="申领">物资申领</option>
                                    <option value="补充">物资补充</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="department" class="form-label">申请科室</label>
                                <input type="text" id="department" class="form-control" required>
                            </div>
                        </div>

                        <!-- 申请物资列表 -->
                        <div class="mb-3">
                            <label class="form-label">申请物资</label>
                            <div id="materialItemsContainer">
                                <div class="input-group mb-2 material-item-row">
                                    <select class="form-select item-select" required>
                                        <option value="">选择物资</option>
                                        ${window.mockData.inventory.map(item => `
                                            <option value="${item.id}" 
                                                    data-name="${item.name}"
                                                    data-unit="${item.unit}">
                                                ${item.name} (${item.unit})
                                            </option>
                                        `).join('')}
                                    </select>
                                    <input type="number" class="form-control item-quantity" placeholder="数量" required min="1">
                                    <input type="text" class="form-control item-unit" readonly>
                                    <button type="button" class="btn btn-danger remove-item-btn">删除</button>
                                </div>
                            </div>
                            <button type="button" class="btn btn-success mt-2" id="addMaterialItemBtn">添加物资</button>
                        </div>

                        <!-- 申请用途和紧急程度 -->
                        <div class="mb-3">
                            <label for="purpose" class="form-label">申请用途</label>
                            <textarea id="purpose" class="form-control" rows="3" required></textarea>
                        </div>

                        <div class="mb-3">
                            <label for="urgency" class="form-label">紧急程度</label>
                            <select id="urgency" class="form-select" required>
                                <option value="普通">普通</option>
                                <option value="紧急">紧急</option>
                                <option value="特急">特急</option>
                            </select>
                        </div>

                        <!-- 预期到货日期 -->
                        <div class="mb-3">
                            <label for="expectedDate" class="form-label">预期到货日期</label>
                            <input type="date" id="expectedDate" class="form-control" required>
                        </div>

                        <!-- 备注信息 -->
                        <div class="mb-3">
                            <label for="notes" class="form-label">备注</label>
                            <textarea id="notes" class="form-control" rows="2"></textarea>
                        </div>

                        <!-- 表单操作按钮 -->
                        <div class="modal-footer">
                            <button type="submit" class="btn btn-primary">提交申请</button>
                            <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">取消</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(modal);

    // 绑定表单提交事件
    document.getElementById('requisitionForm').addEventListener('submit', submitRequisition);
    
    // 绑定物资选择事件（自动填充单位）
    document.querySelectorAll('.item-select').forEach(select => {
        select.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const unitInput = this.closest('.material-item-row').querySelector('.item-unit');
            if (selectedOption.value) {
                unitInput.value = selectedOption.dataset.unit;
            } else {
                unitInput.value = '';
            }
        });
    });

    // 绑定添加物资按钮事件
    document.getElementById('addMaterialItemBtn').addEventListener('click', addRequisitionItemField);
    
    // 绑定删除物资按钮事件
    document.querySelectorAll('.remove-item-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            if (document.querySelectorAll('.material-item-row').length > 1) {
                this.closest('.material-item-row').remove();
            }
        });
    });
}

/**
 * 添加申请物资行
 * 动态添加新的物资选择行到申请表单中
 */
function addRequisitionItemField() {
    const container = document.getElementById('materialItemsContainer');
    const newRow = document.createElement('div');
    newRow.className = 'input-group mb-2 material-item-row';
    newRow.innerHTML = `
        <select class="form-select item-select" required>
            <option value="">选择物资</option>
            ${window.mockData.inventory.map(item => `
                <option value="${item.id}" 
                        data-name="${item.name}"
                        data-unit="${item.unit}">
                    ${item.name} (${item.unit})
                </option>
            `).join('')}
        </select>
        <input type="number" class="form-control item-quantity" placeholder="数量" required min="1">
        <input type="text" class="form-control item-unit" readonly>
        <button type="button" class="btn btn-danger remove-item-btn">删除</button>
    `;
    
    container.appendChild(newRow);

    // 绑定新行的物资选择事件
    const newSelect = newRow.querySelector('.item-select');
    newSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        const unitInput = this.closest('.material-item-row').querySelector('.item-unit');
        if (selectedOption.value) {
            unitInput.value = selectedOption.dataset.unit;
        } else {
            unitInput.value = '';
        }
    });

    // 绑定新行的删除按钮事件
    const newRemoveBtn = newRow.querySelector('.remove-item-btn');
    newRemoveBtn.addEventListener('click', function() {
        if (document.querySelectorAll('.material-item-row').length > 1) {
            this.closest('.material-item-row').remove();
        }
    });
}

/**
 * 提交物资申请
 * 处理物资申领或补充申请的表单提交
 * @param {Event} event - 表单提交事件对象
 */
function submitRequisition(event) {
    event.preventDefault();

    // 获取申请基本信息
    const requisitionType = document.getElementById('requisitionType').value;
    const department = document.getElementById('department').value;
    const purpose = document.getElementById('purpose').value;
    const urgency = document.getElementById('urgency').value;
    const expectedDate = document.getElementById('expectedDate').value;
    const notes = document.getElementById('notes').value;
    
    // 收集申请物资信息
    const items = [];
    document.querySelectorAll('#materialItemsContainer .material-item-row').forEach(row => {
        const itemSelect = row.querySelector('.item-select');
        const itemQuantity = row.querySelector('.item-quantity').value;
        const itemUnit = row.querySelector('.item-unit').value;
        
        if (itemSelect.value && itemQuantity) {
            items.push({
                id: itemSelect.value,
                name: itemSelect.options[itemSelect.selectedIndex].text,
                quantity: parseInt(itemQuantity),
                unit: itemUnit
            });
        }
    });

    // 验证申请信息完整性
    if (items.length === 0) {
        showToast('error', '请至少添加一项物资');
        return;
    }

    // 创建新的申请记录
    const newRequisition = {
        id: 'R' + Date.now(), // 生成唯一申请ID：R + 时间戳
        type: requisitionType,
        department: department,
        items: items,
        purpose: purpose,
        urgency: urgency,
        expectedDate: expectedDate,
        notes: notes,
        status: '待审批',
        applicant: JSON.parse(localStorage.getItem('currentUser')).name,
        applyTime: new Date().toISOString()
    };

    // 初始化申请数组（如果不存在）
    if (!window.mockData.requisitions) {
        window.mockData.requisitions = [];
    }
    // 将新申请添加到数组开头
    window.mockData.requisitions.unshift(newRequisition);

    // 显示成功提示
    showToast('success', '申请提交成功！');
    
    // 关闭模态框
    document.querySelector('.modal').remove();
    
    // 刷新申请列表
    loadRequisitionList();
}

// 加载申请列表
function loadRequisitionList() {
    const tbody = document.getElementById('requisitionListTableBody');
    if (!tbody) return;

    const requisitions = window.mockData.requisitions || [];
    tbody.innerHTML = requisitions.map(req => `
        <tr>
            <td>${req.id}</td>
            <td>${req.type}</td>
            <td>${new Date(req.applyTime).toLocaleString()}</td>
            <td>${req.applicant}</td>
            <td>${req.department}</td>
            <td>${req.items.length}项</td>
            <td>
                <span class="badge bg-${getRequisitionStatusBadgeClass(req.status)}">
                    ${req.status}
                </span>
            </td>
            <td>
                <button class="btn btn-sm btn-info me-1" onclick="showRequisitionDetails('${req.id}')">
                    <i class="fas fa-eye"></i>
                </button>
                ${req.status === '待审批' ? `
                    
                    <button class="btn btn-sm btn-danger" onclick="cancelRequisition('${req.id}')">
                        <i class="fas fa-times"></i>
                    </button>
                ` : ''}
            </td>
        </tr>
    `).join('');
}

// 获取申请状态对应的样式类
function getRequisitionStatusBadgeClass(status) {
    switch (status) {
        case '待审批': return 'warning';
        case '已批准': return 'success';
        case '已拒绝': return 'danger';
        case '已完成': return 'info';
        default: return 'secondary';
    }
}

// 显示申请详情
function showRequisitionDetails(requisitionId) {
    const requisition = window.mockData.requisitions.find(r => r.id === requisitionId);
    if (!requisition) return;

    const modal = document.createElement('div');
    modal.className = 'modal fade show';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">申请详情</h5>
                    <button type="button" class="btn-close" onclick="this.closest('.modal').remove()"></button>
                </div>
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <p><strong>申请编号：</strong>${requisition.id}</p>
                            <p><strong>申请类型：</strong>${requisition.type}</p>
                            <p><strong>申请科室：</strong>${requisition.department}</p>
                            <p><strong>申请人：</strong>${requisition.applicant}</p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>申请时间：</strong>${new Date(requisition.applyTime).toLocaleString()}</p>
                            <p><strong>紧急程度：</strong>${requisition.urgency}</p>
                            <p><strong>期望到货：</strong>${requisition.expectedDate}</p>
                            <p><strong>状态：</strong><span class="badge bg-${getRequisitionStatusBadgeClass(requisition.status)}">${requisition.status}</span></p>
                        </div>
                    </div>

                    <div class="mb-3">
                        <h6>申请物资</h6>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>物资名称</th>
                                        <th>数量</th>
                                        <th>单位</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${requisition.items.map(item => `
                                        <tr>
                                            <td>${item.name}</td>
                                            <td>${item.quantity}</td>
                                            <td>${item.unit}</td>
                                        </tr>
                                    `).join('')}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="mb-3">
                        <h6>申请用途</h6>
                        <p>${requisition.purpose}</p>
                    </div>

                    ${requisition.notes ? `
                        <div class="mb-3">
                            <h6>备注</h6>
                            <p class="border rounded p-2">${requisition.notes}</p>
                        </div>
                    ` : ''}

                    ${requisition.status !== '待审批' ? `
                        <div class="mb-3">
                            <h6>审批信息</h6>
                            <p><strong>审批人：</strong>${requisition.approver}</p>
                            <p><strong>审批时间：</strong>${new Date(requisition.approveTime).toLocaleString()}</p>
                            ${requisition.approveNotes ? `<p><strong>审批意见：</strong>${requisition.approveNotes}</p>` : ''}
                        </div>
                    ` : ''}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">关闭</button>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(modal);
}

// 取消申请
function cancelRequisition(requisitionId) {
    if (confirm('确定要取消该申请吗？')) {
        const index = window.mockData.requisitions.findIndex(r => r.id === requisitionId);
        if (index !== -1) {
            window.mockData.requisitions.splice(index, 1);
            loadRequisitionList();
            showToast('success', '申请已取消');
        }
    }
}

// 筛选申请列表
function filterRequisitions() {
    const searchText = document.getElementById('requisitionSearchInput').value.toLowerCase();
    const statusFilter = document.getElementById('requisitionStatusFilter').value;
    
    const filteredRequisitions = (window.mockData.requisitions || []).filter(req => {
        const matchesSearch = req.id.toLowerCase().includes(searchText) ||
                            req.items.some(item => item.name.toLowerCase().includes(searchText));
        const matchesStatus = statusFilter === 'all' || req.status === statusFilter;
        return matchesSearch && matchesStatus;
    });

    const tbody = document.getElementById('requisitionListTableBody');
    if (tbody) {
        tbody.innerHTML = filteredRequisitions.map(req => `
            <tr>
                <td>${req.id}</td>
                <td>${req.type}</td>
                <td>${new Date(req.applyTime).toLocaleString()}</td>
                <td>${req.applicant}</td>
                <td>${req.department}</td>
                <td>${req.items.length}项</td>
                <td>
                    <span class="badge bg-${getRequisitionStatusBadgeClass(req.status)}">
                        ${req.status}
                    </span>
                </td>
                <td>
                    <button class="btn btn-sm btn-info me-1" onclick="showRequisitionDetails('${req.id}')">
                        <i class="fas fa-eye"></i>
                    </button>
                    ${req.status === '待审批' ? `
                        
                        <button class="btn btn-sm btn-danger" onclick="cancelRequisition('${req.id}')">
                            <i class="fas fa-times"></i>
                        </button>
                    ` : ''}
                </td>
            </tr>
        `).join('');
    }
}

// 添加批准申请的处理函数
function approveRequisition(requisitionId) {
    const requisition = window.mockData.requisitions.find(r => r.id === requisitionId);
    if (!requisition) {
        showToast('error', '未找到申请记录');
        return;
    }

    // 获取当前登录用户信息
    const currentUser = {
        id: 'U001',
        name: '徐主任',
        role: '主任',
        department: '急诊科'
    };

    // 在实际应用中，这里应该调用后端API进行审批
    requisition.status = '已批准';
    requisition.approver = currentUser.name; // 使用当前登录用户的姓名
    requisition.approveTime = new Date().toISOString();
    requisition.approveNotes = '已批准，请尽快安排采购';

    // 更新列表显示
    loadRequisitionList();
    showToast('success', '申请已批准');
}

// 渲染物资异常页面
window.renderMaterialExceptionReport = function() {
    console.log('renderMaterialExceptionReport function called.');
    try {
        const content = `
            <div class="container-fluid">
                <div class="row mb-3">
                    <div class="col">
                        <h4 class="mb-0">物资异常管理</h4>
                    </div>
                    <div class="col-auto">
                        <button class="btn btn-primary" id="newAbnormalBtn">
                            <i class="fas fa-plus"></i> 登记异常
                        </button>
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-body">
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <div class="input-group">
                                    <span class="input-group-text">
                                        <i class="fas fa-search"></i>
                                    </span>
                                    <input type="text" class="form-control" id="abnormalSearchInput" 
                                        placeholder="搜索物资名称、编号或异常类型">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <select class="form-select" id="abnormalStatusFilter">
                                    <option value="all">所有状态</option>
                                    <option value="待处理">待处理</option>
                                    <option value="处理中">处理中</option>
                                    <option value="已解决">已解决</option>
                                </select>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>异常编号</th>
                                        <th>物资名称</th>
                                        <th>异常类型</th>
                                        <th>发现时间</th>
                                        <th>发现人</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="abnormalList">
                                    <!-- 异常列表将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        `;
        document.getElementById('contentArea').innerHTML = content;

        // 绑定事件监听器
        document.getElementById('abnormalSearchInput').addEventListener('keyup', filterAbnormals);
        document.getElementById('abnormalStatusFilter').addEventListener('change', filterAbnormals);
        document.getElementById('newAbnormalBtn').addEventListener('click', showNewAbnormalModal);

        // 事件委托：为动态生成的按钮绑定点击事件
        document.getElementById('abnormalList').addEventListener('click', function(event) {
            const target = event.target.closest('button');
            if (target) {
                const abnormalId = target.dataset.abnormalId;
                if (target.classList.contains('view-details-btn')) {
                    showAbnormalDetails(abnormalId);
                } else if (target.classList.contains('handle-abnormal-btn')) {
                    handleAbnormal(abnormalId);
                }
            }
        });

        // 延迟加载异常列表，确保DOM已更新
        setTimeout(() => {
            loadAbnormalList();
        }, 0);
    } catch (error) {
        console.error("Error rendering material abnormal page:", error);
        showToast('error', '加载物资异常页面失败：' + error.message);
    }
};

// 显示新建异常登记模态框
function showNewAbnormalModal() {
    const modal = `
        <div class="modal fade" id="newAbnormalModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">登记物资异常</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="newAbnormalForm" onsubmit="submitAbnormal(event)">
                            <div class="mb-3">
                                <label class="form-label">物资选择</label>
                                <select class="form-select" name="materialId" required>
                                    <option value="">请选择物资</option>
                                    ${window.mockData.inventory.map(item => `
                                        <option value="${item.id}">${item.name} (${item.id})</option>
                                    `).join('')}
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">异常类型</label>
                                <select class="form-select" name="type" required>
                                    <option value="">请选择异常类型</option>
                                    <option value="过期">过期</option>
                                    <option value="损坏">损坏</option>
                                    <option value="数量不符">数量不符</option>
                                    <option value="质量问题">质量问题</option>
                                    <option value="其他">其他</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">异常描述</label>
                                <textarea class="form-control" name="description" rows="3" required
                                    placeholder="请详细描述异常情况"></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">紧急程度</label>
                                <select class="form-select" name="urgency" required>
                                    <option value="普通">普通</option>
                                    <option value="紧急">紧急</option>
                                    <option value="特急">特急</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">备注</label>
                                <textarea class="form-control" name="notes" rows="2"
                                    placeholder="其他补充信息"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" form="newAbnormalForm" class="btn btn-primary">提交</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', modal);
    const modalInstance = new bootstrap.Modal(document.getElementById('newAbnormalModal'));
    modalInstance.show();
}

// 提交异常登记
function submitAbnormal(event) {
    event.preventDefault();
    try {
        const form = event.target;
        const formData = new FormData(form);
        
        const currentUser = {
            id: 'U001',
            name: '徐主任',
            role: '主任',
            department: '急诊科'
        };

        const abnormal = {
            id: 'AB' + new Date().getTime(),
            materialId: formData.get('materialId'),
            type: formData.get('type'),
            description: formData.get('description'),
            urgency: formData.get('urgency'),
            notes: formData.get('notes'),
            status: '待处理',
            discoverer: currentUser.name, // 使用当前登录用户
            discoverTime: new Date().toISOString(),
            handler: '',
            handleTime: '',
            handleNotes: '',
            handleSteps: []
        };

        // 在实际应用中，这里应该调用后端API保存数据
        window.mockData.abnormals.push(abnormal); // 确保 abnormals 是一个数组

        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('newAbnormalModal'));
        modal.hide();
        document.getElementById('newAbnormalModal').remove();

        // 刷新列表
        loadAbnormalList();
        showToast('success', '异常登记成功');
    } catch (error) {
        console.error("Error submitting abnormal record:", error);
        showToast('error', '登记异常失败：' + error.message);
    }
}

// 加载异常列表
function loadAbnormalList() {
    try {
        const abnormals = window.mockData.abnormals || [];
        const tbody = document.getElementById('abnormalList');
        if (!tbody) {
            console.warn("Abnormal list tbody not found.");
            return;
        }

        tbody.innerHTML = abnormals.map(ab => {
            const material = window.mockData.inventory.find(m => m.id === ab.materialId);
            return `
                <tr>
                    <td>${ab.id}</td>
                    <td>${material ? material.name : '未知物资'}</td>
                    <td>${ab.type}</td>
                    <td>${new Date(ab.discoverTime).toLocaleString()}</td>
                    <td>${ab.discoverer}</td>
                    <td>
                        <span class="badge bg-${getAbnormalStatusBadgeClass(ab.status)}">
                            ${ab.status}
                        </span>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-info me-1 view-details-btn" data-abnormal-id="${ab.id}">
                            <i class="fas fa-eye"></i>
                        </button>
                        ${ab.status === '待处理' ? `
                            <button class="btn btn-sm btn-primary me-1 handle-abnormal-btn" data-abnormal-id="${ab.id}">
                                <i class="fas fa-tools"></i>
                            </button>
                        ` : ''}
                    </td>
                </tr>
            `;
        }).join('');
    } catch (error) {
        console.error("Error loading abnormal list:", error);
        showToast('error', '加载异常列表失败：' + error.message);
    }
}

// 获取异常状态对应的样式类
function getAbnormalStatusBadgeClass(status) {
    switch (status) {
        case '待处理': return 'warning';
        case '处理中': return 'info';
        case '已解决': return 'success';
        default: return 'secondary';
    }
}

// 显示异常详情
function showAbnormalDetails(abnormalId) {
    const abnormal = window.mockData.abnormals.find(a => a.id === abnormalId);
    if (!abnormal) {
        showToast('error', '未找到异常记录');
        return;
    }

    const material = window.mockData.inventory.find(m => m.id === abnormal.materialId);
    const modal = `
        <div class="modal fade" id="abnormalDetailsModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">异常详情</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <p><strong>异常编号：</strong>${abnormal.id}</p>
                                <p><strong>物资名称：</strong>${material ? material.name : '未知物资'}</p>
                                <p><strong>异常类型：：</strong>${abnormal.type}</p>
                                <p><strong>紧急程度：</strong>${abnormal.urgency}</p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>发现时间：</strong>${new Date(abnormal.discoverTime).toLocaleString()}</p>
                                <p><strong>发现人：：</strong>${abnormal.discoverer}</p>
                                <p><strong>状态：</strong>
                                    <span class="badge bg-${getAbnormalStatusBadgeClass(abnormal.status)}">
                                        ${abnormal.status}
                                    </span>
                                </p>
                            </div>
                        </div>
                        <div class="mb-3">
                            <h6>异常描述</h6>
                            <p class="border rounded p-2">${abnormal.description}</p>
                        </div>
                        ${abnormal.notes ? `
                            <div class="mb-3">
                                <h6>备注</h6>
                                <p class="border rounded p-2">${abnormal.notes}</p>
                            </div>
                        ` : ''}
                        ${abnormal.handleSteps.length > 0 ? `
                            <div class="mb-3">
                                <h6>处理记录</h6>
                                <div class="timeline">
                                    ${abnormal.handleSteps.map(step => `
                                        <div class="timeline-item">
                                            <div class="timeline-marker"></div>
                                            <div class="timeline-content">
                                                <h6 class="mb-1">${step.action}</h6>
                                                <p class="mb-1">${step.notes}</p>
                                                <small class="text-muted">
                                                    ${new Date(step.time).toLocaleString()} - ${step.operator}
                                                </small>
                                            </div>
                                        </div>
                                    `).join('')}
                                </div>
                            </div>
                        ` : ''}
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', modal);
    const modalInstance = new bootstrap.Modal(document.getElementById('abnormalDetailsModal'));
    modalInstance.show();
}

// 处理异常
function handleAbnormal(abnormalId) {
    const abnormal = window.mockData.abnormals.find(a => a.id === abnormalId);
    if (!abnormal) {
        showToast('error', '未找到异常记录');
        return;
    }

    const modal = `
        <div class="modal fade" id="handleAbnormalModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">处理异常</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="handleAbnormalForm" onsubmit="submitHandleAbnormal(event, '${abnormalId}')">
                            <div class="mb-3">
                                <label class="form-label">处理操作</label>
                                <select class="form-select" name="action" required>
                                    <option value="">请选择处理操作</option>
                                    <option value="开始处理">开始处理</option>
                                    <option value="更新进度">更新进度</option>
                                    <option value="完成处理">完成处理</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">处理说明</label>
                                <textarea class="form-control" name="notes" rows="3" required
                                    placeholder="请详细说明处理情况"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" form="handleAbnormalForm" class="btn btn-primary">提交</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', modal);
    const modalInstance = new bootstrap.Modal(document.getElementById('handleAbnormalModal'));
    modalInstance.show();
}

// 提交异常处理
function submitHandleAbnormal(event, abnormalId) {
    event.preventDefault();
    try {
        const form = event.target;
        const formData = new FormData(form);
        
        const currentUser = {
            id: 'U001',
            name: '徐主任',
            role: '主任',
            department: '急诊科'
        };

        // 添加处理记录
        abnormal.handleSteps.push({
            action: action,
            notes: notes,
            operator: currentUser.name,
            time: new Date().toISOString()
        });

        // 更新异常状态
        if (action === '开始处理') {
            abnormal.status = '处理中';
            abnormal.handler = currentUser.name;
            abnormal.handleTime = new Date().toISOString();
        } else if (action === '完成处理') {
            abnormal.status = '已解决';
            abnormal.handleNotes = notes;
        }

        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('handleAbnormalModal'));
        modal.hide();
        document.getElementById('handleAbnormalModal').remove();

        // 刷新列表
        loadAbnormalList();
        showToast('success', '处理记录已更新');
    } catch (error) {
        console.error("Error submitting abnormal record:", error);
        showToast('error', '登记异常失败：' + error.message);
    }
}

// 筛选异常列表
function filterAbnormals() {
    const searchText = document.getElementById('abnormalSearchInput').value.toLowerCase();
    const statusFilter = document.getElementById('abnormalStatusFilter').value;
    
    const abnormals = window.mockData.abnormals || [];
    const filteredAbnormals = abnormals.filter(ab => {
        const material = window.mockData.inventory.find(m => m.id === ab.materialId);
        const materialName = material ? material.name.toLowerCase() : '';
        
        const matchesSearch = materialName.includes(searchText) ||
            ab.id.toLowerCase().includes(searchText) ||
            ab.type.toLowerCase().includes(searchText);
        
        const matchesStatus = statusFilter === 'all' || ab.status === statusFilter;
        
        return matchesSearch && matchesStatus;
    });

    const tbody = document.getElementById('abnormalList');
    if (!tbody) return;

    tbody.innerHTML = filteredAbnormals.map(ab => {
        const material = window.mockData.inventory.find(m => m.id === ab.materialId);
        return `
            <tr>
                <td>${ab.id}</td>
                <td>${material ? material.name : '未知物资'}</td>
                <td>${ab.type}</td>
                <td>${new Date(ab.discoverTime).toLocaleString()}</td>
                <td>${ab.discoverer}</td>
                <td>
                    <span class="badge bg-${getAbnormalStatusBadgeClass(ab.status)}">
                        ${ab.status}
                    </span>
                </td>
                <td>
                    <button class="btn btn-sm btn-info me-1 view-details-btn" data-abnormal-id="${ab.id}">
                        <i class="fas fa-eye"></i>
                    </button>
                    ${ab.status === '待处理' ? `
                        <button class="btn btn-sm btn-primary me-1 handle-abnormal-btn" data-abnormal-id="${ab.id}">
                            <i class="fas fa-tools"></i>
                        </button>
                    ` : ''}
                </td>
            </tr>
        `;
    }).join('');
}

// 渲染物资使用历史页面
window.renderMaterialUsageHistory = function() {
    const contentDiv = document.getElementById('contentArea');
    if (!contentDiv) return;

    contentDiv.innerHTML = `
        <h2 class="mb-4">物资使用历史</h2>
        <div class="card">
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-5">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" class="form-control" id="usageHistorySearchInput" placeholder="搜索操作人、物资名称、地点...">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" id="usageHistoryTypeFilter">
                            <option value="all">所有类型</option>
                            <option value="出库">出库记录</option>
                            <option value="入库">入库记录</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <input type="date" class="form-control" id="usageHistoryDateFilter">
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>记录编号</th>
                                <th>操作时间</th>
                                <th>操作类型</th>
                                <th>操作人</th>
                                <th>物资明细</th>
                                <th>相关急救车</th>
                                <th>地点</th>
                                <th>备注</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="usageHistoryTableBody">
                            <!-- 历史记录将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;

    // 设置日期筛选器默认值为今天
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('usageHistoryDateFilter').value = today;

    // 绑定事件监听器
    document.getElementById('usageHistorySearchInput').addEventListener('keyup', filterUsageHistory);
    document.getElementById('usageHistoryTypeFilter').addEventListener('change', filterUsageHistory);
    document.getElementById('usageHistoryDateFilter').addEventListener('change', filterUsageHistory);

    // 初始加载历史记录
    loadUsageHistoryList();
};

// 加载物资使用历史列表
function loadUsageHistoryList() {
    const tbody = document.getElementById('usageHistoryTableBody');
    if (!tbody) return;

    // 确保 window.mockData.usageRecords 存在且为数组
    if (!window.mockData.usageRecords || !Array.isArray(window.mockData.usageRecords)) {
        window.mockData.usageRecords = [];
    }

    const records = window.mockData.usageRecords;
    tbody.innerHTML = records.map(record => {
        const ambulance = window.mockData.ambulances.find(amb => amb.id === record.ambulanceId);
        const ambulanceDisplay = ambulance ? `${ambulance.plateNumber} (${ambulance.department})` : '无';

        return `
            <tr>
                <td>${record.id}</td>
                <td>${new Date(record.operationTime).toLocaleString()}</td>
                <td><span class="badge bg-${record.type === '出库' ? 'danger' : 'success'}">${record.type}</span></td>
                <td>${record.operator}</td>
                <td>
                    <button class="btn btn-sm btn-info" onclick="showRecordItems('${record.id}')">
                        <i class="fas fa-list"></i> 查看明细
                    </button>
                </td>
                <td>${ambulanceDisplay}</td>
                <td>${record.location || '-'}</td>
                <td>${record.notes || '-'}</td>
                <td>
                    <button class="btn btn-sm btn-secondary" onclick="exportRecord('${record.id}')">
                        <i class="fas fa-download"></i>
                    </button>
                </td>
            </tr>
        `;
    }).join('');
}

// 筛选物资使用历史记录
function filterUsageHistory() {
    const searchTerm = document.getElementById('usageHistorySearchInput').value.toLowerCase();
    const typeFilter = document.getElementById('usageHistoryTypeFilter').value;
    const dateFilter = document.getElementById('usageHistoryDateFilter').value;
    
    const filteredRecords = (window.mockData.usageRecords || []).filter(record => {
        const matchesSearch = (
            record.operator.toLowerCase().includes(searchTerm) ||
            (record.items && record.items.some(item => item.name.toLowerCase().includes(searchTerm))) ||
            (record.location && record.location.toLowerCase().includes(searchTerm))
        );
        const matchesType = typeFilter === 'all' || record.type === typeFilter;
        const matchesDate = !dateFilter || record.operationTime.startsWith(dateFilter);

        return matchesSearch && matchesType && matchesDate;
    });

    const tbody = document.getElementById('usageHistoryTableBody');
    if (tbody) {
        tbody.innerHTML = filteredRecords.map(record => {
            const ambulance = window.mockData.ambulances.find(amb => amb.id === record.ambulanceId);
            const ambulanceDisplay = ambulance ? `${ambulance.plateNumber} (${ambulance.department})` : '无';

            return `
                <tr>
                    <td>${record.id}</td>
                    <td>${new Date(record.operationTime).toLocaleString()}</td>
                    <td><span class="badge bg-${record.type === '出库' ? 'danger' : 'success'}">${record.type}</span></td>
                    <td>${record.operator}</td>
                    <td>
                        <button class="btn btn-sm btn-info" onclick="showRecordItems('${record.id}')">
                            <i class="fas fa-list"></i> 查看明细
                        </button>
                    </td>
                    <td>${ambulanceDisplay}</td>
                    <td>${record.location || '-'}</td>
                    <td>${record.notes || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-secondary" onclick="exportRecord('${record.id}')">
                            <i class="fas fa-download"></i>
                        </button>
                    </td>
                </tr>
            `;
        }).join('');
    }
}

// 占位符：导出记录功能
function exportRecord(recordId) {
    showToast('info', `导出记录 ${recordId} 功能待实现`);
    console.log('导出记录:', recordId);
}

// 渲染物资有效期预警页面
window.renderMaterialExpiryAlerts = function() {
    const contentDiv = document.getElementById('contentArea');
    if (!contentDiv) return;

    contentDiv.innerHTML = `
        <h2 class="mb-4">物资有效期预警</h2>
        <div class="card">
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-4">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" class="form-control" id="expirySearchInput" placeholder="搜索物资名称、编号...">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" id="expiryStatusFilter">
                            <option value="all">所有状态</option>
                            <option value="expired">已过期</option>
                            <option value="warning">即将过期</option>
                            <option value="normal">正常</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" id="expiryDaysFilter">
                            <option value="all">所有时间</option>
                            <option value="7">7天内过期</option>
                            <option value="15">15天内过期</option>
                            <option value="30">30天内过期</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button class="btn btn-primary w-100" onclick="exportExpiryReport()">
                            <i class="fas fa-download me-2"></i>导出报告
                        </button>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>物资编号</th>
                                <th>物资名称</th>
                                <th>所在急救车</th>
                                <th>所在层级</th>
                                <th>生产日期</th>
                                <th>有效期至</th>
                                <th>剩余天数</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="expiryAlertsTableBody">
                            <!-- 预警记录将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;

    // 绑定事件监听器
    document.getElementById('expirySearchInput').addEventListener('keyup', filterExpiryAlerts);
    document.getElementById('expiryStatusFilter').addEventListener('change', filterExpiryAlerts);
    document.getElementById('expiryDaysFilter').addEventListener('change', filterExpiryAlerts);

    // 初始加载预警列表
    loadExpiryAlerts();
};

/**
 * 加载物资有效期预警列表
 * 实现功能：对即将过期、过期或者小于最低数量的物资进行报警
 * 计算每个物资的剩余有效期天数，并标识过期状态
 */
function loadExpiryAlerts() {
    const tbody = document.getElementById('expiryAlertsTableBody');
    if (!tbody) return;

    // 获取所有急救车中的物资
    const allItems = [];
    window.mockData.ambulances.forEach(ambulance => {
        ambulance.layers.forEach(layer => {
            layer.items.forEach(item => {
                // 为每个物资添加位置信息
                allItems.push({
                    ...item,
                    ambulanceId: ambulance.id,
                    ambulancePlate: ambulance.plateNumber,
                    layerId: layer.id,
                    layerName: layer.name
                });
            });
        });
    });

    // 计算每个物资的剩余有效期天数，并从inventory中获取完整的物资信息
    const today = new Date();
    const itemsWithExpiry = allItems.map(item => {
        const expiryDate = new Date(item.expiryDate);
        // 计算剩余天数（向上取整）
        const daysUntilExpiry = Math.ceil((expiryDate - today) / (1000 * 60 * 60 * 24));
        
        // 根据剩余天数确定状态
        let status = 'normal';
        if (daysUntilExpiry < 0) {
            status = 'expired';      // 已过期
        } else if (daysUntilExpiry <= 30) {
            status = 'warning';      // 即将过期（30天内）
        }

        // 从inventory中获取完整的物资信息，包括生产日期
        const fullItemDetails = window.mockData.inventory.find(invItem => invItem.id === item.id);
        const productionDate = fullItemDetails && fullItemDetails.productionDate ? 
            new Date(fullItemDetails.productionDate).toLocaleDateString() : '未指定';

        return {
            ...item,
            daysUntilExpiry,
            status,
            productionDate
        };
    });

    // 按剩余天数排序（已过期和即将过期的排在前面）
    itemsWithExpiry.sort((a, b) => a.daysUntilExpiry - b.daysUntilExpiry);

    // 渲染表格
    tbody.innerHTML = itemsWithExpiry.map(item => {
        // 根据状态确定CSS类和显示文本
        const statusClass = item.status === 'expired' ? 'danger' : 
                          item.status === 'warning' ? 'warning' : 'success';
        const statusText = item.status === 'expired' ? '已过期' : 
                          item.status === 'warning' ? '即将过期' : '正常';

        return `
            <tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.ambulancePlate}</td>
                <td>${item.layerName}</td>
                <td>${item.productionDate}</td>
                <td>${new Date(item.expiryDate).toLocaleDateString()}</td>
                <td>${item.daysUntilExpiry < 0 ? '已过期' : item.daysUntilExpiry + '天'}</td>
                <td><span class="badge bg-${statusClass}">${statusText}</span></td>
                <td>
                    <button class="btn btn-sm btn-info me-1" onclick="showItemDetails('${item.id}')">
                        <i class="fas fa-info-circle"></i>
                    </button>
                    <button class="btn btn-sm btn-warning" onclick="handleExpiredItem('${item.id}')">
                        <i class="fas fa-exclamation-triangle"></i>
                    </button>
                </td>
            </tr>
        `;
    }).join('');
}

/**
 * 筛选物资有效期预警
 * 根据搜索词、状态和剩余天数进行筛选
 */
function filterExpiryAlerts() {
    const searchTerm = document.getElementById('expirySearchInput').value.toLowerCase();
    const statusFilter = document.getElementById('expiryStatusFilter').value;
    const daysFilter = document.getElementById('expiryDaysFilter').value;

    const tbody = document.getElementById('expiryAlertsTableBody');
    if (!tbody) return;

    const rows = tbody.getElementsByTagName('tr');
    Array.from(rows).forEach(row => {
        const itemName = row.cells[1].textContent.toLowerCase();    // 物资名称
        const itemId = row.cells[0].textContent.toLowerCase();      // 物资ID
        const status = row.cells[7].textContent.trim();             // 状态文本
        const daysUntilExpiry = parseInt(row.cells[6].textContent) || 0; // 剩余天数

        // 搜索条件匹配
        const matchesSearch = itemName.includes(searchTerm) || itemId.includes(searchTerm);
        
        // 状态筛选匹配
        const matchesStatus = statusFilter === 'all' || 
            (statusFilter === 'expired' && status === '已过期') ||
            (statusFilter === 'warning' && status === '即将过期') ||
            (statusFilter === 'normal' && status === '正常');
        
        // 天数筛选匹配
        const matchesDays = daysFilter === 'all' || 
            (daysUntilExpiry <= parseInt(daysFilter) && daysUntilExpiry >= 0);

        // 显示或隐藏行
        row.style.display = matchesSearch && matchesStatus && matchesDays ? '' : 'none';
    });
}

/**
 * 显示物资详情
 * 显示指定物资的详细信息，包括基本信息和位置信息
 * @param {string} itemId - 物资ID
 */
function showItemDetails(itemId) {
    // 查找物资信息
    let itemInAmbulance = null;
    let ambulanceInfo = null;
    let layerInfo = null;

    // 遍历急救车，找到指定物资所在的急救车和层级信息
    for (const ambulance of window.mockData.ambulances) {
        for (const layer of ambulance.layers) {
            const item = layer.items.find(i => i.id === itemId);
            if (item) {
                itemInAmbulance = item;
                ambulanceInfo = ambulance;
                layerInfo = layer;
                break; // 找到即跳出内层循环
            }
        }
        if (itemInAmbulance) {
            break; // 找到即跳出外层循环
        }
    }

    // 从 inventory 中获取完整的物资详细信息
    const fullItemDetails = window.mockData.inventory.find(item => item.id === itemId);

    if (!itemInAmbulance || !fullItemDetails) {
        showToast('error', '未找到物资信息');
        return;
    }

    // 整合信息，以 inventory 中的详细信息为主，ambulance 中的位置和状态为辅
    const itemInfoToDisplay = {
        ...fullItemDetails,
        ...itemInAmbulance, // 合并信息，itemInAmbulance中的同名字段会覆盖fullItemDetails中的
        // 确保生产日期和过期日期格式正确
        productionDate: fullItemDetails.productionDate ? new Date(fullItemDetails.productionDate).toLocaleDateString() : '未指定',
        expiryDate: fullItemDetails.expiryDate ? new Date(fullItemDetails.expiryDate).toLocaleDateString() : '未指定',
        location: itemInAmbulance.location || fullItemDetails.location || '未指定' // 优先使用急救车中的位置，其次是inventory中的位置
    };

    // 创建并显示模态框
    const modal = document.createElement('div');
    modal.className = 'modal fade show';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">物资详情</h5>
                    <button type="button" class="btn-close" onclick="this.closest('.modal').remove()"></button>
                </div>
                <div class="modal-body">
                    <!-- 基本信息 -->
                    <div class="mb-3">
                        <h6>基本信息</h6>
                        <p><strong>物资编号：</strong> ${itemInfoToDisplay.id}</p>
                        <p><strong>物资名称：</strong> ${itemInfoToDisplay.name}</p>
                        <p><strong>规格：</strong> ${itemInfoToDisplay.specification || '未指定'}</p>
                        <p><strong>生产厂家：</strong> ${itemInfoToDisplay.manufacturer || '未指定'}</p>
                    </div>
                    <!-- 有效期信息 -->
                    <div class="mb-3">
                        <h6>有效期信息</h6>
                        <p><strong>生产日期：</strong> ${itemInfoToDisplay.productionDate}</p>
                        <p><strong>有效期至：</strong> ${itemInfoToDisplay.expiryDate}</p>
                        <p><strong>存储条件：</strong> ${itemInfoToDisplay.storageCondition || '未指定'}</p>
                    </div>
                    <!-- 位置信息 -->
                    <div class="mb-3">
                        <h6>位置信息</h6>
                        <p><strong>所在急救车：</strong> ${ambulanceInfo.plateNumber} (${ambulanceInfo.department})</p>
                        <p><strong>所在层级：</strong> ${layerInfo.name}</p>
                        <p><strong>存放位置：</strong> ${itemInfoToDisplay.location}</p>
                    </div>
                    ${itemInfoToDisplay.notes ? `
                        <!-- 备注信息 -->
                        <div class="mb-3">
                            <h6>备注</h6>
                            <p>${itemInfoToDisplay.notes}</p>
                        </div>
                    ` : ''}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">关闭</button>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(modal);
}

// 处理过期物资
function handleExpiredItem(itemId) {
    // 查找物资信息
    let itemInfo = null;
    let ambulanceInfo = null;
    let layerInfo = null;

    window.mockData.ambulances.forEach(ambulance => {
        ambulance.layers.forEach(layer => {
            const item = layer.items.find(i => i.id === itemId);
            if (item) {
                itemInfo = item;
                ambulanceInfo = ambulance;
                layerInfo = layer;
            }
        });
    });

    if (!itemInfo) {
        showToast('error', '未找到物资信息');
        return;
    }

    // 创建并显示处理模态框
    const modal = document.createElement('div');
    modal.className = 'modal fade show';
    modal.style.display = 'block';
    modal.innerHTML = `
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">处理过期物资</h5>
                    <button type="button" class="btn-close" onclick="this.closest('.modal').remove()"></button>
                </div>
                <div class="modal-body">
                    <form id="handleExpiredItemForm" onsubmit="submitHandleExpiredItem(event, '${itemId}')">
                        <div class="mb-3">
                            <label class="form-label">物资信息</label>
                            <p><strong>${itemInfo.name}</strong> (${itemInfo.id})</p>
                            <p>有效期至：${new Date(itemInfo.expiryDate).toLocaleDateString()}</p>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">处理方式</label>
                            <select class="form-select" name="handleType" required>
                                <option value="">请选择处理方式</option>
                                <option value="return">退回供应商</option>
                                <option value="destroy">销毁处理</option>
                                <option value="replace">更换新批次</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">处理说明</label>
                            <textarea class="form-control" name="handleNotes" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">处理人</label>
                            <input type="text" class="form-control" name="handler" required>
                        </div>
                        <div class="text-end">
                            <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">取消</button>
                            <button type="submit" class="btn btn-primary">提交</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    `;

    document.body.appendChild(modal);
}

// 提交过期物资处理
function submitHandleExpiredItem(event, itemId) {
    event.preventDefault();
    const form = event.target;
    const formData = new FormData(form);
    
    // 在实际应用中，这里应该调用后端API保存处理记录
    // 这里仅做演示，显示成功提示
    showToast('success', '处理记录已提交');
    form.closest('.modal').remove();
    
    // 刷新预警列表
    loadExpiryAlerts();
}

// 导出有效期预警报告
function exportExpiryReport() {
    // 在实际应用中，这里应该生成并下载报告文件
    // 这里仅做演示，显示提示信息
    showToast('info', '导出报告功能待实现');
}

// 渲染物资库存预警页面
window.renderMaterialInventoryAlerts = function() {
    const contentDiv = document.getElementById('contentArea');
    if (!contentDiv) return;

    contentDiv.innerHTML = `
        <h2 class="mb-4">物资库存预警</h2>
        <div class="card">
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-5">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" class="form-control" id="inventoryAlertSearchInput" placeholder="搜索物资名称、编号...">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <select class="form-select" id="inventoryAlertStatusFilter">
                            <option value="all">所有状态</option>
                            <option value="low_stock">库存不足</option>
                            <option value="normal">库存正常</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <button class="btn btn-primary w-100" onclick="exportInventoryAlertReport()">
                            <i class="fas fa-download me-2"></i>导出报告
                        </button>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>物资编号</th>
                                <th>物资名称</th>
                                <th>当前库存</th>
                                <th>最低库存</th>
                                <th>库存状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="inventoryAlertsTableBody">
                            <!-- 库存预警记录将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;

    // 绑定事件监听器
    document.getElementById('inventoryAlertSearchInput').addEventListener('keyup', filterInventoryAlerts);
    document.getElementById('inventoryAlertStatusFilter').addEventListener('change', filterInventoryAlerts);

    // 初始加载预警列表
    loadInventoryAlerts();
};

/**
 * 加载物资库存预警列表
 * 实现功能：对即将过期、过期或者小于最低数量的物资进行报警
 * 检查所有物资的库存状态，标识库存不足的物资
 */
function loadInventoryAlerts() {
    const tbody = document.getElementById('inventoryAlertsTableBody');
    if (!tbody) return;

    // 获取所有物资
    const allInventoryItems = window.mockData.inventory || [];

    // 计算每个物资的库存状态并筛选出库存不足的物资
    const itemsToDisplay = allInventoryItems.map(item => {
        let status = 'normal';
        if (item.quantity < item.minQuantity) {
            status = 'low_stock'; // 库存不足
        }
        return {
            ...item,
            inventoryStatus: status
        };
    });

    // 将实际需要预警（库存不足）的物资存储到 mockData 中，供导出功能使用
    // 这里的 `inventoryAlerts` 应该只包含 `low_stock` 的项
    window.mockData.inventoryAlerts = itemsToDisplay.filter(item => item.inventoryStatus === 'low_stock');
    console.log('loadInventoryAlerts - window.mockData.inventoryAlerts:', window.mockData.inventoryAlerts);

    // 优先显示库存不足的物资
    itemsToDisplay.sort((a, b) => {
        if (a.inventoryStatus === 'low_stock' && b.inventoryStatus !== 'low_stock') return -1;
        if (a.inventoryStatus !== 'low_stock' && b.inventoryStatus === 'low_stock') return 1;
        return 0;
    });

    // 渲染表格
    tbody.innerHTML = itemsToDisplay.map(item => {
        const statusClass = item.inventoryStatus === 'low_stock' ? 'danger' : 'success';
        const statusText = item.inventoryStatus === 'low_stock' ? '库存不足' : '库存正常';

        return `
            <tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.quantity} ${item.unit}</td>
                <td>${item.minQuantity} ${item.unit}</td>
                <td><span class="badge bg-${statusClass}">${statusText}</span></td>
                <td>
                    <button class="btn btn-sm btn-info me-1" onclick="showItemDetails('${item.id}')">
                        <i class="fas fa-info-circle"></i>
                    </button>
                    ${item.inventoryStatus === 'low_stock' ? `
                    <button class="btn btn-sm btn-warning" onclick="handleLowStockItem('${item.id}')">
                        <i class="fas fa-exclamation-triangle"></i> 处理
                    </button>
                    ` : ''}
                </td>
            </tr>
        `;
    }).join('');
}

/**
 * 筛选物资库存预警
 * 根据搜索词和状态进行筛选
 */
function filterInventoryAlerts() {
    const searchTerm = document.getElementById('inventoryAlertSearchInput').value.toLowerCase();
    const statusFilter = document.getElementById('inventoryAlertStatusFilter').value;

    const tbody = document.getElementById('inventoryAlertsTableBody');
    if (!tbody) return;

    const allInventoryItems = window.mockData.inventory || [];

    // 筛选物资
    const filteredItems = allInventoryItems.filter(item => {
        const itemName = item.name.toLowerCase();
        const itemId = item.id.toLowerCase();
        const matchesSearch = itemName.includes(searchTerm) || itemId.includes(searchTerm);

        // 确定物资状态
        let itemStatus = 'normal';
        if (item.quantity < item.minQuantity) {
            itemStatus = 'low_stock';
        }

        const matchesStatus = statusFilter === 'all' || itemStatus === statusFilter;

        return matchesSearch && matchesStatus;
    });

    // 将筛选出的低库存物资存储到 mockData 中，供导出功能使用
    // 这里的 `inventoryAlerts` 应该只包含 `low_stock` 的项，且是当前筛选条件下的
    window.mockData.inventoryAlerts = filteredItems.filter(item => item.quantity < item.minQuantity);
    console.log('filterInventoryAlerts - window.mockData.inventoryAlerts:', window.mockData.inventoryAlerts);

    // 渲染表格
    tbody.innerHTML = filteredItems.map(item => {
        const statusClass = item.quantity < item.minQuantity ? 'danger' : 'success';
        const statusText = item.quantity < item.minQuantity ? '库存不足' : '库存正常';

        return `
            <tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.quantity} ${item.unit}</td>
                <td>${item.minQuantity} ${item.unit}</td>
                <td><span class="badge bg-${statusClass}">${statusText}</span></td>
                <td>
                    <button class="btn btn-sm btn-info me-1" onclick="showItemDetails('${item.id}')">
                        <i class="fas fa-info-circle"></i>
                    </button>
                    ${item.quantity < item.minQuantity ? `
                    <button class="btn btn-sm btn-warning" onclick="handleLowStockItem('${item.id}')">
                        <i class="fas fa-exclamation-triangle"></i> 处理
                    </button>
                    ` : ''}
                </td>
            </tr>
        `;
    }).join('');
}

/**
 * 处理库存不足物资
 * 占位符函数，用于处理库存不足物资的操作
 * @param {string} itemId - 物资ID
 */
function handleLowStockItem(itemId) {
    showToast('info', `处理物资 ${itemId} 库存不足问题功能待实现。建议进行申领！`);
    console.log('处理库存不足物资:', itemId);
}

/**
 * 导出库存预警报告
 * 将库存预警数据导出为CSV格式文件
 */
function exportInventoryAlertReport() {
    try {
        const alerts = window.mockData.inventoryAlerts || [];
        console.log('exportInventoryAlertReport - Attempting to export alerts:', alerts);
        
        if (alerts.length === 0) {
            showToast('info', '没有需要导出的库存预警');
            return;
        }

        // 准备导出数据，添加中文列名
        const exportData = alerts.map(item => ({
            '物资编号': item.id,
            '物资名称': item.name,
            '类别': item.category || '未知',
            '当前库存': item.quantity,
            '最低库存': item.minQuantity,
            '单位': item.unit || '未知',
            '存放位置': item.location || '未指定',
            '状态': '库存不足',
            '预警时间': new Date().toLocaleString()
        }));

        // 调用CSV导出函数
        exportToCSV(exportData, `库存预警报告_${new Date().toLocaleDateString()}.csv`);
        showToast('success', '库存预警报告导出成功');
    } catch (error) {
        console.error('导出库存预警报告时发生错误:', error);
        showToast('error', '导出库存预警报告失败');
    }
}

/**
 * 渲染物资资料查询页面
 * 实现功能：可对各种数据进行有效查询和管理
 */
window.renderMaterialDataQuery = function() {
    const contentDiv = document.getElementById('contentArea');
    if (!contentDiv) return;

    // 构建物资资料查询页面HTML结构
    contentDiv.innerHTML = `
        <h2 class="mb-4">物资资料查询</h2>
        <div class="card">
            <div class="card-body">
                <!-- 搜索和筛选区域 -->
                <div class="row mb-3">
                    <div class="col-md-5">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" class="form-control" id="materialDataSearchInput" placeholder="搜索物资名称、编号...">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <select class="form-select" id="materialDataCategoryFilter">
                            <option value="all">所有类别</option>
                            <option value="急救药品">急救药品</option>
                            <option value="基础药品">基础药品</option>
                            <option value="医疗设备">医疗设备</option>
                            <option value="手术器械">手术器械</option>
                            <option value="消毒用品">消毒用品</option>
                            <option value="手术耗材">手术耗材</option>
                            <option value="医疗耗材">医疗耗材</option>
                            <option value="儿科药品">儿科药品</option>
                            <option value="儿科设备">儿科设备</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <button class="btn btn-primary w-100" onclick="exportMaterialDataReport()">
                            <i class="fas fa-download me-2"></i>导出报告
                        </button>
                    </div>
                </div>
                
                <!-- 物资资料表格 -->
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>物资编号</th>
                                <th>物资名称</th>
                                <th>类别</th>
                                <th>当前库存</th>
                                <th>最低库存</th>
                                <th>有效期至</th>
                                <th>供应商</th>
                                <th>存放位置</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="materialDataTableBody">
                            <!-- 物资资料将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;

    // 初始化物资资料列表
    loadMaterialDataList();
    
    // 添加搜索和筛选事件监听
    document.getElementById('materialDataSearchInput').addEventListener('input', filterMaterialData);
    document.getElementById('materialDataCategoryFilter').addEventListener('change', filterMaterialData);
};

/**
 * 加载物资资料列表
 * 从mockData中获取物资数据并渲染到表格中
 */
function loadMaterialDataList() {
    const tbody = document.getElementById('materialDataTableBody');
    if (!tbody) return;

    const materials = window.mockData.inventory || [];
    
    // 将物资数据转换为HTML表格行
    tbody.innerHTML = materials.map(item => `
        <tr>
            <td>${item.id}</td>
            <td>${item.name}</td>
            <td>${item.category || '未分类'}</td>
            <td>${item.quantity} ${item.unit}</td>
            <td>${item.minQuantity} ${item.unit}</td>
            <td>${item.expiryDate ? new Date(item.expiryDate).toLocaleDateString() : '未指定'}</td>
            <td>${item.supplier || '未指定'}</td>
            <td>${item.location || '未指定'}</td>
            <td>
                <button class="btn btn-sm btn-info" onclick="showItemDetails('${item.id}')">
                    <i class="fas fa-info-circle"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

/**
 * 筛选物资资料
 * 根据搜索词和类别进行筛选
 */
function filterMaterialData() {
    const searchTerm = document.getElementById('materialDataSearchInput').value.toLowerCase();
    const categoryFilter = document.getElementById('materialDataCategoryFilter').value;

    const tbody = document.getElementById('materialDataTableBody');
    if (!tbody) return;

    const materials = window.mockData.inventory || [];
    
    // 筛选物资
    const filteredMaterials = materials.filter(item => {
        const itemName = item.name.toLowerCase();
        const itemId = item.id.toLowerCase();
        const matchesSearch = itemName.includes(searchTerm) || itemId.includes(searchTerm);
        const matchesCategory = categoryFilter === 'all' || item.category === categoryFilter;

        return matchesSearch && matchesCategory;
    });

    // 渲染筛选后的表格
    tbody.innerHTML = filteredMaterials.map(item => `
        <tr>
            <td>${item.id}</td>
            <td>${item.name}</td>
            <td>${item.category || '未分类'}</td>
            <td>${item.quantity} ${item.unit}</td>
            <td>${item.minQuantity} ${item.unit}</td>
            <td>${item.expiryDate ? new Date(item.expiryDate).toLocaleDateString() : '未指定'}</td>
            <td>${item.supplier || '未指定'}</td>
            <td>${item.location || '未指定'}</td>
            <td>
                <button class="btn btn-sm btn-info" onclick="showItemDetails('${item.id}')">
                    <i class="fas fa-info-circle"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

/**
 * 导出物资资料报告
 * 将物资资料数据导出为CSV格式文件
 */
function exportMaterialDataReport() {
    const items = window.mockData.inventory || [];
    
    // 准备导出数据，添加中文列名
    const exportData = items.map(item => ({
        '物资编号': item.id,
        '物资名称': item.name,
        '类别': item.category || '未分类',
        '当前库存': item.quantity,
        '最低库存': item.minQuantity,
        '单位': item.unit || '未知',
        '有效期至': item.expiryDate ? new Date(item.expiryDate).toLocaleDateString() : '未指定',
        '供应商': item.supplier || '未指定',
        '存放位置': item.location || '未指定',
        '规格': item.specification || '未指定',
        '生产厂家': item.manufacturer || '未指定'
    }));

    // 调用CSV导出函数
    exportToCSV(exportData, `物资资料报告_${new Date().toLocaleDateString()}.csv`);
}

// 渲染医生角色的首页仪表盘
window.renderDashboard = function() {
    const contentArea = document.getElementById('contentArea');
    if (!contentArea) return;

    // 统计急救车状态
    const ambulanceStatuses = window.mockData.ambulances.reduce((acc, ambulance) => {
        const status = ambulance.status;
        acc[status] = (acc[status] || 0) + 1;
        return acc;
    }, {});

    // 统计物资库存状态
    const inventoryStatuses = window.mockData.inventory.reduce((acc, item) => {
        const status = item.quantity < item.minQuantity ? '库存不足' : '库存正常';
        acc[status] = (acc[status] || 0) + 1;
        return acc;
    }, {});

    // 统计物资有效期状态
    const expiryStatuses = { expired: 0, warning: 0, normal: 0 };
    const today = new Date();
    window.mockData.ambulances.forEach(ambulance => {
        ambulance.layers.forEach(layer => {
            layer.items.forEach(item => {
                const expiryDate = new Date(item.expiryDate);
                const daysUntilExpiry = Math.ceil((expiryDate - today) / (1000 * 60 * 60 * 24));
                if (daysUntilExpiry < 0) {
                    expiryStatuses.expired++;
                } else if (daysUntilExpiry <= 30) {
                    expiryStatuses.warning++;
                } else {
                    expiryStatuses.normal++;
                }
            });
        });
    });

    contentArea.innerHTML = `
        <h2 class="dashboard-title">首页概览</h2>
        <div class="row">
            <!-- 急救车状态概览 -->
            <div class="col-md-4 mb-4">
                <div class="card text-white bg-primary">
                    <div class="card-header dashboard-card-header">急救车状态</div>
                    <div class="card-body">
                        <h5 class="card-title">总数: ${window.mockData.ambulances.length}辆</h5>
                        <p class="card-text">可用: ${ambulanceStatuses['可用'] || 0}辆</p>
                        <p class="card-text">使用中: ${ambulanceStatuses['使用中'] || 0}辆</p>
                        <p class="card-text">维护中: ${ambulanceStatuses['维修中'] || 0}辆</p>
                    </div>
                </div>
            </div>

            <!-- 物资库存概览 -->
            <div class="col-md-4 mb-4">
                <div class="card text-white bg-success">
                    <div class="card-header dashboard-card-header">物资库存概览</div>
                    <div class="card-body">
                        <h5 class="card-title">总物资种类: ${window.mockData.inventory.length}种</h5>
                        <p class="card-text">库存正常: ${inventoryStatuses['库存正常'] || 0}种</p>
                        <p class="card-text">库存不足: ${inventoryStatuses['库存不足'] || 0}种</p>
                    </div>
                </div>
            </div>

            <!-- 物资有效期概览 -->
            <div class="col-md-4 mb-4">
                <div class="card text-white bg-info">
                    <div class="card-header dashboard-card-header">物资有效期概览</div>
                    <div class="card-body">
                        <h5 class="card-title">总物资项: ${window.mockData.ambulances.reduce((sum, amb) => sum + amb.layers.reduce((lSum, layer) => lSum + layer.items.length, 0), 0)}项</h5>
                        <p class="card-text">正常: ${expiryStatuses.normal}项</p>
                        <p class="card-text">即将过期: ${expiryStatuses.warning}项</p>
                        <p class="card-text">已过期: ${expiryStatuses.expired}项</p>
                    </div>
                </div>
            </div>
        </div>
    `;
};// 导出数据工具函数
function exportToCSV(data, filename) {
    try {
        // 将数据转换为CSV格式
        const headers = Object.keys(data[0]);
        const csvContent = [
            headers.join(','),
            ...data.map(row => headers.map(header => {
                const value = row[header];
                // 处理包含逗号、引号或换行符的值
                if (value === null || value === undefined) return '';
                const stringValue = String(value);
                if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) {
                    return `"${stringValue.replace(/"/g, '""')}"`;
                }
                return stringValue;
            }).join(','))
        ].join('\n');

        // 创建Blob对象
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        
        // 创建下载链接
        const link = document.createElement('a');
        if (link.download !== undefined) {
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    } catch (error) {
        console.error('导出数据时发生错误:', error);
        showToast('error', '导出数据失败');
    }
}

// 更新导出记录函数
function exportRecord(recordId) {
    const record = window.mockData.usageRecords.find(r => r.id === recordId);
    if (!record) {
        showToast('error', '未找到相关记录');
        return;
    }

    // 准备导出数据
    const exportData = {
        recordId: record.id,
        ambulancePlate: record.ambulancePlate,
        department: record.department,
        usageTime: record.usageTime,
        operator: record.operator,
        purpose: record.purpose,
        notes: record.notes || '',
        items: record.items.map(item => ({
            materialName: item.name,
            quantity: item.quantity,
            unit: item.unit
        }))
    };

    exportToCSV([exportData], `使用记录_${record.id}_${new Date().toLocaleDateString()}.csv`);
}

// 更新导出过期报告函数
function exportExpiryReport() {
    const expiredItems = window.mockData.expiryAlerts || [];
    if (expiredItems.length === 0) {
        showToast('info', '没有需要导出的过期物资');
        return;
    }

    exportToCSV(expiredItems, `过期物资报告_${new Date().toLocaleDateString()}.csv`);
}

// 更新导出库存预警报告函数
function exportInventoryAlertReport() {
    const lowStockItems = window.mockData.inventoryAlerts || [];
    if (lowStockItems.length === 0) {
        showToast('info', '没有需要导出的库存预警');
        return;
    }

    exportToCSV(lowStockItems, `库存预警报告_${new Date().toLocaleDateString()}.csv`);
}

// 更新导出物资资料报告函数
function exportMaterialDataReport() {
    const materials = window.mockData.inventory || [];
    if (materials.length === 0) {
        showToast('info', '没有需要导出的物资资料');
        return;
    }

    exportToCSV(materials, `物资资料报告_${new Date().toLocaleDateString()}.csv`);
}

